package cn.yl.course.server.controller;


import cn.yl.api.server.result.Result;
import cn.yl.api.server.util.redis.RedisUtils;
import cn.yl.course.server.entity.Course;
import cn.yl.course.server.entity.dto.CourseDto;
import cn.yl.course.server.service.CourseService;
import cn.yl.course.server.service.OrderFeignService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author yl
 * @since 2022-04-22
 */

@RestController
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private OrderFeignService orderFeignService;

    private final CourseService courseService;

    public CourseController(CourseService courseService) {
        this.courseService = courseService;
    }


    @GetMapping("getAllCourse")
    public Result getAllCourse() {
//        new ThreadPoolExecutor()
//        ExecutorService es = Executors.newFixedThreadPool(20);
//        for (int i = 1; i <= 20; i++) {
//            es.submit(new Runnable() {
//                @Override
//                public void run() {
//                    courseService.getAllCourse();
//                }
//            });
//        }

        List<CourseDto> allCourseDto = courseService.getAllCourse();
        return Result.ok().setData("items", allCourseDto);
    }

    @GetMapping("getMyCoursesById")
    public Result getMyCoursesByIds(HttpServletRequest request) {
        String jwt = request.getHeader("jwt");
        Result okOrderCourseIds = orderFeignService.getOKOrderCourseIds(jwt);
        ArrayList<Integer> ids = (ArrayList<Integer>) okOrderCourseIds.getData().get("items");
        List<CourseDto> courseDtoList = null;
        if (ids.size() > 0) {
            courseDtoList = courseService.getByIds(ids);
        }
        return Result.ok().setData("items", courseDtoList);
    }

    @GetMapping("getCourseById")
    public Map<String ,Object> getCourseById(Integer courseId){
        HashMap<String, Object> map = new HashMap<>();
        Course course = this.courseService.getById(courseId);
        map.put("courseId",course.getId());
        map.put("price",course.getPrice());
        map.put("discounts",course.getDiscounts());
        return map;
    }

    @PutMapping("{courseId}")
    public void updateSalesByCourseId(@PathVariable Integer courseId){
        this.courseService.updateSalesAndRedis(courseId);

    }
}

